# /bin/bash
# Build docker image
# Copyright (c)  MarsBighead. 2024. All rights reserved.
#
#openGauss is licensed under Mulan PSL v2.
#You can use this software according to the terms and conditions of the Mulan PSL v2.
#You may obtain a copy of Mulan PSL v2 at:
#
#          http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
#-------------------------------------------------------------------------
#
# build.sh
#    Build docker image
#
# IDENTIFICATION
#    phant-container/ci/build.sh
#
#-------------------------------------------------------------------------
set -eu
# Parameters
VERSION="5.0.0"
SKIPCHECKSUM=0
DOCKEROPS=""
MIN_DOCKER_VERSION_MAJOR="17"
MIN_DOCKER_VERSION_MINOR="09"

HOME_DIR=$(cd $(dirname $0);cd ../;pwd)
IMAGES_DIR=${HOME_DIR}/images

# Need to add extension to support more install mode. 
INSTALL_MODE=lite

function usage() {
  cat << EOF

Usage: build.sh -v [version]  [-i]  [Docker build option]
Builds a Docker Image for openGauss
  
Parameters:
   -v: version to build
   -i: ignores the SHA256 checksums

LICENSE MulanPSL2
EOF
}

# Validate packages
function checksum_packages() {
if [ "${arch}" = "amd64" ]; then
    sha256_file="sha256_file_amd64"
    else
    sha256_file="sha256_file_arm64"
fi

  if hash sha256sum 2>/dev/null; then
    echo "Checking if required packages are present and valid..."   
    if ! sha256sum -c "$sha256_file"; then
      echo "SHA256 for required packages to build this image did not match!"
      echo "Make sure to download missing files in folder $VERSION."
      exit 1;
    fi
  else
    echo "Ignored SHA256 sum, 'sha256sum' command not available.";
  fi
}
# Check Docker version
function check_docker_version() {
  # Get Docker Server version
  echo "Checking Docker version."
  DOCKER_VERSION=$(docker version --format '{{.Server.Version | printf "%.5s" }}'|| exit 0)
  # Remove dot in Docker version
  docker_version_major=$(echo $DOCKER_VERSION | awk -F . '{print $1}')

  if [ -z "$DOCKER_VERSION" ]; then
    # docker could be aliased to podman and errored out (https://github.com/containers/libpod/pull/4608)
    echo "Please check if docker is installed." && exit 1
  elif [ "$docker_version_major" -lt "${MIN_DOCKER_VERSION_MAJOR}" ]; then
    echo "Docker version is below the minimum required version $MIN_DOCKER_VERSION_MAJOR.$MIN_DOCKER_VERSION_MINOR"
    echo "Please upgrade your Docker installation to proceed."
    exit 1;
  fi
}


function get_dockerfile(){
  INSTALL_MODE=$1
  DOCKERFILE=$2
  case $INSTALL_MODE in 
    lite)  echo "${IMAGES_DIR}/lite/${DOCKERFILE}";;
    *   )  echo "${IMAGES_DIR}/lite/Dockerfile";;
  esac
}

function unpack_lite_pkg(){
  dockerfile=$1
  VERSION=$2
  install_package_dir=$3
  install_package_bin_name=$4
  install_dir=$(dirname ${dockerfile})/opengauss-${VERSION}
  mkdir -p ${install_dir}
  tar zxf ${install_package_dir} -C ${install_dir}
  cd ${install_dir}
  tar zxf ${install_package_bin_name}
  rm ${install_package_bin_name} 
  install_package_bin_sha256=$(echo ${install_package_bin_name}| awk -F '.bin' '{print $1}').sha256
  rm ${install_package_bin_sha256} 
  pwd
  ls -lth
  tar zxf upgrade_sql.tar.gz
  rm upgrade_sql.tar.gz upgrade_sql.sha256 
  cd -
}

function remove_install_pkg(){
  dockerfile=$1
  VERSION=$2
  install_dir=$(dirname ${dockerfile})/opengauss-${VERSION}
  rm -rf ${install_dir}
}

function build_image(){
  IMAGE_NAME=$1
  dockerfile=$2
  VERSION=$3
  pwd
  echo "Building image '$IMAGE_NAME' with dockerfile ${dockerfile} ..."

  # BUILD THE IMAGE (replace all environment variables)
  BUILD_START=$(date '+%s')
  docker build --force-rm=true --no-cache=true \
       $DOCKEROPS \
       --build-arg="GAUSS_VERSION=${VERSION}"  \
       -t $IMAGE_NAME -f $dockerfile . || {
  echo ""
  echo "ERROR: openGauss Database Docker Image was NOT successfully created."
  echo "ERROR: Check the output and correct any reported problems with the docker build operation."
  exit 1
  }
}
##############
#### MAIN ####
##############

# docker build  -t gauss-openeuler-os:22.03 -f Dockerfile_os .



function main() {
  arch=""
  case $(uname -m) in 
    i386 ) arch="386";;
    i686 ) arch="386" ;; 
    x86_64 ) arch="amd64";; 
    aarch64)  arch="arm64";;  
    arm64  )  arch="arm64"  
  esac
  
 
  if [ "${arch}" = "amd64" ]; then
    DOCKERFILE="Dockerfile_amd"
  else
    DOCKERFILE="Dockerfile"
  fi
  
  if [ "$#" -eq 0 ]; then
    usage;
    exit 1;
  fi
  
  while getopts "hesxiv:o:" optname; do
    case "$optname" in
      "h")
        usage
        exit 0;
        ;;
      "i")
        SKIPCHECKSUM=1
        ;;
      "v")
        VERSION="$OPTARG"
        ;;
      "o")
        DOCKEROPS="$OPTARG"
        ;;
      "?")
        usage;
        exit 1;
        ;;
      *)
      # Should not occur
        echo "Unknown error while processing options inside buildDockerImage.sh"
        ;;
    esac
  done
  echo $VERSION
  cd ${IMAGES_DIR}
  # openGauss Database Image Name
  IMAGE_NAME="opengauss:$VERSION"
  case $INSTALL_MODE in 
    enterprise) IMAGE_NAME="opengauss-enterprise:$VERSION";;
    lite) 
      cd lite
      IMAGE_NAME="opengauss-lite:$VERSION";;
    *   )  IMAGE_NAME="opengauss:$VERSION";;
  esac
  # to-do: simplify get package name with different version
  #        under variable install mode

  OPENGUASS_VERSION_MAJOR=$(echo $VERSION | awk -F '.' '{print $1}')
  
  dockerfile=$(get_dockerfile $INSTALL_MODE $DOCKERFILE)
  echo $(dirname $dockerfile)
  echo "OPENGUASS VERSION MAJOR is  ${OPENGUASS_VERSION_MAJOR}"
  case $OPENGUASS_VERSION_MAJOR in
    "6" ) 
      # images/openGauss-Lite-6.0.0-openEuler22.03-aarch64.tar.gz
      install_package_bin_name="openGauss-Lite-${VERSION}-openEuler22.03-aarch64.bin"
      install_package_name="openGauss-Lite-${VERSION}-openEuler22.03-aarch64.tar.gz"
      ;;
    "5" ) 
      install_package_bin_name="openGauss-Lite-${VERSION}-openEuler-aarch64.bin"
      install_package_name="openGauss-Lite-${VERSION}-openEuler-aarch64.tar.gz"
      ;;
    *)
      install_package_bin_name="openGauss-Lite-${VERSION}-openEuler-aarch64.bin"
      install_package_name="openGauss-Lite-${VERSION}-openEuler-aarch64.tar.gz"
      ;;
  esac
  echo "Unpackage openGauss installation package ${install_package_name} on $(hostname)"
  unpack_lite_pkg $dockerfile ${VERSION} ${IMAGES_DIR}/${install_package_name} ${install_package_bin_name}
  #exit
  echo "Building image '$IMAGE_NAME' ..."
  build_image $IMAGE_NAME  $dockerfile $VERSION

  echo "Remove openGauss installation package files."
  remove_install_pkg ${dockerfile} ${VERSION}

}

main $@
